package com.open.yujiakj.core.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.Base64Codec;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author honglei
 * @version 1.0
 * @description: TODO
 * @date 2025/5/23 9:56
 */
public class JwtUtil {
    /**
     * 生成Token
     */

    public void testJWTBuilder(){
        long now = System.currentTimeMillis();
        long exp = now + 60 * 1000;
        JwtBuilder jwtBuilder= Jwts.builder()
                //设置id，{"jti":""}
                .setId("9527")
                //{"sub":""}
                .setSubject("JJWT")
                //{"iat":""}
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,"xxxxx")
                //过期时间，指定从现在开始到什么时候过期,{"exp":""}
                .setExpiration(new Date(exp))
                //自定义声明，参数map
                //.addClaims()
                .claim("name","xiaoqiang")
                .claim("中国","加油");

        //生成token
        String token = jwtBuilder.compact();
        System.out.println(token);

        String[] split=token.split("\\.");

        System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
        System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
        System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
    }

    /**
     * Token解析
     */

    public void testJWTToken(){
        String token = "eyJhbGciOiJIUzI1NiJ9." +
                "eyJqdGkiOiI5NTI3Iiwic3ViIjoiSkpXVCIsImlhdCI6MTYyOTQ0MTE2OSwiZXhwIjoxNjI5NDQxMjI5LCJuYW1lIjoieGlhb3FpYW5nIiwi5Lit5Zu9Ijoi5Yqg5rK5In0" +
                ".ztKcVF5r5hwQ7X4qwhH-NvWmdWELXImxIDRWiaCSzq8";

        Claims claims = Jwts.parser().setSigningKey("xxxxx")
                .parseClaimsJws(token).getBody();

        System.out.println("jti:"+claims.getId());
        System.out.println("sub:"+claims.getSubject());
        System.out.println("iat:"+claims.getIssuedAt());
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("iat:"+format.format(claims.getIssuedAt()));
        System.out.println("exp:"+format.format(claims.getExpiration()));
        System.out.println("name:"+claims.get("name"));
        System.out.println("中国:"+claims.get("中国"));

    }
}
